import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Button, Icon, Form, Select, InputNumber } from 'antd'
import _ from 'lodash'

const FormItem = Form.Item
const Option = Select.Option

@Form.create()
export default class ItemSelect extends PureComponent {

  static propTypes = {
    items: PropTypes.object,
    value: PropTypes.any,
    onChange: PropTypes.func,
    style: PropTypes.object
  }

  static defaultProps = {
    items: null,
    value: null,
    onChange: () => {},
    style: null
  }

  constructor (props) {
    super(props)
    this.uuid = 0
    this.uItems = []
    this.initialize = true
  }
  
  componentWillReceiveProps (nextProps) {
    const { value } = nextProps
    const itemKeys = this.props.form.getFieldValue('item-keys')
    if (value !== this.props.value && this.initialize) {
      this.initialize = false
      for (let item of value) {
        this.add(_.zipObject(['name', 'num'], item.split(',')))
      }
    }
    itemKeys.length === 0 && this.resetFields()
  }

  render () {
    const { form, items, value, style } = this.props
    const { getFieldDecorator, getFieldValue } = form
    getFieldDecorator('item-keys', { initialValue: [] })
    const itemKeys = getFieldValue('item-keys')
    const itemOptions = _.keys(items).map(d => {
      let isHideOption = _.find(this.uItems, o => o.name === d)
      return (
        <Option 
          key={d} 
          value={d} 
          disabled={isHideOption !== undefined}
          >
          {items[d]}
        </Option>
      )
    })
    return (
      <div style={style}>
        <Form
          >
          {itemKeys.map((k, index) => {
            let itemNode = _.find(this.uItems, o => o.key === k)
            return (
              <FormItem
                required={false}
                key={k}
                >
                {getFieldDecorator(`item-name-${k}`, {
                  rules: [{ required: true, message: '请选择物品!' }],
                  initialValue: itemNode.name || undefined
                })(
                  <Select 
                    showSearch
                    placeholder="物品名称" 
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                    style={{ width: 340, marginRight: 8 }}
                    onChange={this.onChangeSelectItem.bind(this, k, 'name')}
                    >
                    {itemOptions}
                  </Select>
                )}
                <InputNumber defaultValue={1} style={{ width: 120 }} onChange={this.onChangeSelectItem.bind(this, k, 'num')} />
                <Icon
                  type="close-circle-o"
                  style={{ marginLeft: 10 }}
                  onClick={this.remove.bind(this, k)}
                  />
              </FormItem>
            )
          })}
        </Form>
        <Button type="dashed" onClick={this.add} style={{ width: 500 }}>
          <Icon type="plus" /> 添加物品
        </Button>
      </div>
    )
  }

  add = (item = null) => {
    this.uuid++
    const itemKeys = this.props.form.getFieldValue('item-keys')
    const nextKeys = itemKeys.concat(this.uuid)
    this.props.form.setFieldsValue({
      'item-keys': nextKeys,
    })
    this.uItems.push({ 
      key: this.uuid, 
      num: 1,
      ...item
    })
  }

  remove = (k) => {
    const itemKeys = this.props.form.getFieldValue('item-keys')
    this.props.form.setFieldsValue({
      'item-keys': itemKeys.filter(key => key !== k)
    })
    _.remove(this.uItems, e => e.key === k)
    this.onChange()
  }

  onChangeSelectItem = (k, n, value) => {
    _.find(this.uItems, { key: k })[n] = value
    this.onChange()
  }

  onChange () {
    let itemValues = []
    for (let item of this.uItems) {
      item.name && item.num !== 0 && itemValues.push(`${item.name},${item.num}`)
    }
    this.props.onChange(itemValues)
  }

  resetFields () {
    this.uItems = []
    this.uuid = 0
  }
}